package com.eiisan.user.service.impl;

import com.eiisan.base.constant.GlobalConstant;
import com.eiisan.core.util.api.Result;
import com.eiisan.user.model.dto.UserInfoDto;
import com.eiisan.user.model.dto.UserLoginDto;
import com.eiisan.user.service.AuthorityService;
import com.eiisan.user.service.LoginService;
import com.eiisan.user.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Description: 登录管理服务
 * @Author: gragonfly
 * @Date: 2019/6/25
 */
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private AuthorityService authorityService;
    @Autowired
    private RedisService redisService;

    @Override
    public Result<String> login(UserLoginDto param) {
        if (param == null) {
            return Result.errorRequest();
        }
        Result<UserInfoDto> result = authorityService.getUserInfoByMobile(param.getMobile());
        if (Result.isNotSuccess(result)) {
            return Result.fail(result.getMessage());
        }
        UserInfoDto userInfoDto = result.getData();
        if(!userInfoDto.getPassword().equals(param.getPassword())){
            return Result.fail("用户名或密码错误");
        }
        String loginKey = GlobalConstant.User.LOGIN_KEY + userInfoDto.getUserId();

        String token = generatorToken(loginKey);

        if (redisService.getKey(loginKey) != null) {
            return Result.fail("用户已登录");
        }

        redisService.setKey(token,"",30L, TimeUnit.MINUTES);



        return null;
    }

    private String generatorToken(String prefix){
        return prefix + UUID.randomUUID().toString().replace("-","");
    }
}
